/*-------------------------------------------------
   工作流  组件
    开发人：tss
    开发时间：2010-08-23
    修改人： 
---------------------------------------------------*/
var graph;   //视图设计对象

var templateProp;  //模板动态表格

var nodeProp;  //节点动态表格

var preSelectCell;   //前一个选中对象

var editStart = true;  //编辑开始状态

/**
 * 获得生成ID
 * @return
 */
function getGenId(){
	
	var r = 0;
	//new Date().getTime();
	with(Math){
		for(var i = 0; i < 5; i++){
			var n = round(random() * 10);
			r += ""+n;
		}
	}
	return r;
}

/**
 * 初始化方法
 * @return
 */
var workflowInit = function(){
	
	instantSave();
	
	var getChkStr = function(op){
		return "<input type=\"checkbox\" name=\"chk_"+op+"_id\" value=\"${rowId}\"/>";

	};
	
	var getName = function(op){
		return  "<input type=\"text\" name=\""+op+"Name\" style=\"width:50px\"/>";
		
	};
	var getValue = function(op){
		return "<input type=\"text\" name=\""+op+"Value\" style=\"width:100px\" />";
		
	};
	
	//***********  模板属性动态表格初始化 start***************//
	templateProp = new DyTable("tbTemplateProp","templateProp");
	templateProp.delCallFun = function(){
		
	};
	templateProp.config.trClsName = "tb_c";
	var pop = "templateProp";
	templateProp.config.tdHtml = [getChkStr(pop),getName(pop),getValue(pop)];
	templateProp.config.chkIds = "chk_templateProp_id";
	templateProp.config.autoDelOp = true;
	templateProp.config.setDelCallFun(delVariable);
	
	// 事件注册
	templateProp.registerEvent(templateProp.eventType.add, "template_prop_add",addVariable);
	templateProp.registerEvent(templateProp.eventType.delAll, "template_prop_del",delVariable);
	
	//***********  模板属性动态表格初始化 end***************//
	
	
	//*********** 节点属性动态表格初始化  start***************//
	nodeProp = new DyTable("tbNodeProp","nodeProp");
	nodeProp.delCallFun = function(){
		
	};
	nodeProp.config.trClsName = "tb_c";
	pop = "nodeProp";
	nodeProp.config.tdHtml = [getChkStr(pop),getName(pop),getValue(pop)];
	nodeProp.config.chkIds = "chk_nodeProp_id";
	nodeProp.config.autoDelOp = true;
	nodeProp.config.setDelCallFun(delVariable);
	
	// 事件注册
	nodeProp.registerEvent(nodeProp.eventType.add, "node_prop_add",addVariable);
	nodeProp.registerEvent(nodeProp.eventType.delAll, "node_prop_del",delVariable);
	
	//*********** 节点属性动态表格初始化  end***************//
	
	// 初始化模板
	initWorkFlow();
	var op = $("#operate").val();
	var jsonStr = $("#hiddenProcess").text();
	if(jsonStr == null || jsonStr == ""){
		newTemplate();
		document.getElementById("graphContainer").onclick();   //初始化模板选中状态
	}else{
		loadTemplate(jsonStr,false);
	}
	if(op != "newEdit"){
		editStart = false;
	}
	
	$("#positionDiv").css("display","block");
	$("#graphContainer").append($("#positionDiv"));
	
	
	// 保存初始化历史
	saveHistory();
	
	
};

/**
 * 删除变量
 * @param dyRows
 * @return
 */
function delVariable(dyRows){
	for(dyRow in dyRows){
		window.bindCell.form.variableMap.remove(dyRow.id);
	}
}

/**
 * 添加变量
 * @param dyRows
 * @return
 */
function addVariable(dyRows){
	
	if(typeof(window.bindCell.form.variableMap) == "undefined"){
		
		window.bindCell.form.variableMap = new Map();
	}
	
	
}

/**
 * 变量类
 * @param name
 * @param value
 * @return
 */
var Variable = function(name,value){
	this.name = name;
	this.value = value;
};

/**
 * 初始化模板
 * 
 * @return
 */
function initWorkFlow(){

	var graphContainer = document.getElementById("graphContainer");
	graphContainer.innerHTML = "";

	//实例化试图设计对象
	graph = new mxGraph(graphContainer);
	

	
	graph.container = graphContainer;  // 设计器容器
	//graphContainer.graph = graph;

	// 试图组件初始化
	graph.setConnectable(true);
	graph.setTooltips(true);
	graph.isPort = function (cell) {
		var geo = this.getCellGeometry(cell);
		return (geo != null) ? geo.relative : false;
	};
	graph.getTooltipForCell = function (cell) {
		if (this.model.isEdge(cell)) {
			return this.convertValueToString(this.model.getTerminal(cell, true)) + " => " + this.convertValueToString(this.model.getTerminal(cell, false));
		}
		return mxGraph.prototype.getTooltipForCell.apply(this, arguments);
	};
	graph.isCellFoldable = function (cell) {
		return false;
	};
	new mxRubberband(graph);
	
	graph.parent = graph.getDefaultParent();
	
	//var style = graph.getStylesheet().getDefaultEdgeStyle();
	//style[mxConstants.STYLE_EDGE] = mxEdgeStyle.ElbowConnector;
	//style[mxConstants.STYLE_ROUNDED] = true;
	//style[mxConstants.STYLE_EDGE] = mxEdgeStyle.TopToBottom;
	//graph.alternateEdgeStyle = 'elbow=arrow';

	// 初始化流程模板属性窗口
	document.forms[2].reset();
	
	// 流程模板属性初始化
	var title = "未命名流程模板";
	graph.historys = new Array();  // 历史版本容器
	graph.historyNum = 0;            // 历史版本索引号
	graph.form = new Object();
	graph.form.variableMap = new Map();  
	window.bindCell = graph; // V
	window.bindCell.name = title;
	window.bindCell.value = title;
	window.bindCell.form.id = "";
	window.bindCell.form.key = "wmmmb1";
	window.bindCell.form.version = "1";
	window.bindCell.form.description = "暂无描述";
	window.bindCell.formName = document.forms[2].name;
	


	 // 增加tag标题
	$("<span class='tagTitleSelected'>"+title+"</span>").appendTo("#tagTitles");

    // 标记其它操作启用
	//$("a").removeClass("deny");
	

}

/**
 * 新建模板
 * 
 * @return
 */
function newTemplate(){
    
    createNode("ellipse","开始","start","",350,50,50,50,"red","white");
    
    createNode("ellipse","结束","end","",350,450,50,50,"red","white");

}



/**
 * 创建节点
 * 
 * @param shape
 * @param name
 * @param category
 * @param image
 * @param posLeft
 * @param posTop
 * @param foregroundColor
 * @param backgroundColor
 * @return
 */
function createNode(shape,name,category,image,posLeft,posTop,posWidth,posHeight,foregroundColor,backgroundColor) {
	
	graph.getModel().beginUpdate();
	if(typeof(posLeft) == "undefined"){
		posLeft = DEFAULT_POSLEFT;
	}
	if(typeof(posTop) == "undefined"){
		posTop = DEFAULT_POSTOP;
	}
	if(typeof(posWidth) == "undefined"){
		posWidth = DEFAULT_WIDTH;
	}
	if(typeof(posHeight) == "undefined"){
		posHeight = DEFAULT_HEIGHT;
	}
	if(typeof(category) == "undefined"){
		category = DEFAULT_CATEGORY;
	}
	if(typeof(foregroundColor) == "undefined"){
		foregroundColor = "#000000";
	}
	if(typeof(backgroundColor) == "undefined"){
		backgroundColor = "white";
	}
	
	var id = getGenId();
	jsonObject = {"cssStyle":{"posLeft":posLeft,"posTop":posTop,"posWidth":posWidth,"posHeight":posHeight,"styleShape":shape,"image":image,"foregroundColor":foregroundColor,"backgroundColor":backgroundColor},
			"form":{"id":id,"name":name,"category":category}};
	
	if(category != "start" && category != "end"){
		jsonObject.taskCategory = "share";  //默认为共享任务
	}
	uniflowNode = new WorkFlowNode(jsonObject);
	uniflowNode.draw(jsonObject.cssStyle.posLeft, jsonObject.cssStyle.posTop, jsonObject.cssStyle.posWidth, jsonObject.cssStyle.posHeight);
	uniflowNode.syna(); 
	if(category != "start" && category != "end"){
		graph.selectNextCell();
	}
	graph.getModel().endUpdate();
	return(uniflowNode);
}

/**
 * 创建链接
 * @param source
 * @param tagert
 * @param cell
 * @return
 */
function createLink(name,source,tagert,_cell){
	
	var id = linkIdGen.getId();
	var jsonObj = {"id":id,"name":name};
	var link = new WorkFlowLink(jsonObj);
    link.draw(source,tagert,_cell);
	link.syna(); 
    return link;
}

/**
 * 加载模板
 * 
 * @param jsonData
 * @return
 */
function loadTemplate(jsonStr,isNew){
	
	var jsonData = eval('(' +jsonStr+ ')');
	var nodeArray = jsonData.nodeArray;
	
	// 流程模板设置
	window.bindCell = graph;
	window.bindCell.value = jsonData.form.name;
	window.bindCell.variableMap = new Map();
	for(var prop in jsonData.form){
		if(prop == "variableMap"){
			var dataList = jsonData.form[prop].dataList;
			if(dataList != null && dataList.length > 0){
				for(var i = 0; i < dataList.length; i++){
					var data = dataList[i];
					window.bindCell.form[prop].put(data.key,data.value);
				}
			}
		}else{
			window.bindCell.form[prop] = jsonData.form[prop];
			$("#template").find("#"+prop).val(jsonData.form[prop]);
		}
    }
	showVariable(templateProp, window.bindCell);
    
	// 节点设置
	for(var i = 0; i < nodeArray.length; i++){
		
		var nodeJsonObj = nodeArray[i];
		var nodeCell = createNodeCellByJson(nodeJsonObj,isNew);
		
		var linkArray = nodeJsonObj.linkArray;
		if(linkArray == null || linkArray.length == 0){
			continue;
		}
		
		// 链接设置
		for(var j = 0; j < linkArray.length; j++){
			
			var linkJsonObj = linkArray[j];
			var inputCell = getNodeCellById(nodeArray,linkJsonObj.form.inputNodeId);
			var outputCell = getNodeCellById(nodeArray,linkJsonObj.form.outputNodeId);
			var uniflowLink = new WorkFlowLink(linkJsonObj);
			uniflowLink.draw(inputCell,outputCell,null);
			uniflowLink.syna();
		}
	}
}

/**
 * 展示变量表单
 * 
 * @param prop
 * @param cell
 * @return
 */
function showVariable(prop,cell){
	
	prop.delAllRow();
	if(typeof(cell.form.variableMap) != "undefined"){
		var dataList = cell.form.variableMap.dataList;
		for(var i = 0; i < dataList.length; i++){
			var variable = dataList[i].value;
			prop.config.tdHtmlValue = ["text|"+variable.name,"text|"+variable.value];
			prop.addFullRow();
		}
	}
}

/**
 * 清空变量表单
 * 
 * @param varNameStart
 * @param cell
 * @return
 */
function clearVariable(varNameStart,cell){
	
	var varNames = document.getElementsByName(varNameStart + "Name");
	var varValues = document.getElementsByName(varNameStart + "Value");
	cell.form.variableMap.clear();
	if(varNames != null){
		for(var i = 0; i < varNames.length; i++){
			var rowId = varNames[i].parentNode.parentNode.id;
			var variable = new Variable(varNames[i].value,varValues[i].value);
			cell.form.variableMap.put(rowId,variable);
		}
	}
}


/**
 * 获得节点
 * 
 * @param nodeArry
 * @param id
 * @return
 */
function getNodeCellById(nodeArray,id){
	for(var i = 0; i < nodeArray.length; i++){
		var nodeJsonObj = nodeArray[i];
		if(nodeJsonObj.form.id == id){
			return createNodeCellByJson(nodeJsonObj,false);
		}
	}
	return null;
}


/**
 * 创建节点
 * 
 * @param jsonObject
 * @return
 */
function createNodeCellByJson(jsonObject,isNew){
	
	if(!isNew){
		
		// 先从grap 中取
		var id = jsonObject.form.id;
		var cells = graph.getChildVertices(graph.parent);
		if(cells != null && cells.length > 0){
			for(var i = 0; i < cells.length; i++){
				var cell = cells[i];
				if(cell.form.id == id){
					return cell;
				}
			}
		}
	}
	
	// 没有就创建
	graph.getModel().beginUpdate();
	var uniflowNode = new WorkFlowNode(jsonObject);
	uniflowNode.draw(jsonObject.cssStyle.posLeft, jsonObject.cssStyle.posTop, jsonObject.cssStyle.posWidth, jsonObject.cssStyle.posHeight);
	uniflowNode.syna();
	// graph.selectNextCell();
	graph.getModel().endUpdate();
	return uniflowNode.cell;
}


/**
 * 保存流程模板
 */
function saveTemplate() {
	
	var vertexCells =  graph.getChildVertices(graph.parent);
	var jsons = new Array();
	
	var JsonTemplate = function(){
		var jt = new Object();
		jt = {"form":{},"nodeArray":[]};
		return jt;
	};
	var JsonNode = function(){
		var jn = new Object();
		jn = {"form":{},"cssStyle":{}};
		return jn;
	};
	var JsonLink = function(){
		var jl = new Object();
		jl = {"form":{},"cssStyle":{}};
		return jl;
	};
	
	var jsonTemplate = new JsonTemplate();
	
	//获得模板信息
    for (var prop in graph.form) {
    	jsonTemplate.form[prop] = graph.form[prop];
    }
    
    if(vertexCells == null || vertexCells.length == 0){
    	  throw(new   Error(-1,   "没有节点! "));
    }
    
    for(var i = 0; i < vertexCells.length; i++){
    	  var node = vertexCells[i];
		  if(node == null){
			  continue;
		  }
		  
		  //获得节点信息
		  var jsonNode = new JsonNode();
		  for(var prop in node.form){
			  // alert(prop);
			  jsonNode.form[prop] = node.form[prop];
		  }
		  for(var prop in node.cssStyle){
			  jsonNode.cssStyle[prop] = node.cssStyle[prop];
		  }
		  jsonTemplate.nodeArray.push(jsonNode);
		  
		  //获得链接信息
		  var linkArray = graph.getOutgoingEdges(node,graph.parent);
		  if(linkArray == null || linkArray.length == 0){
		      continue;
		  }
		  jsonNode.linkArray = new Array();
		  for(var j = 0; j < linkArray.length; j++){
			  var link = linkArray[j];
			  if(link == null){
				  continue;
			  }
			  var jsonLink = new JsonLink();
			  for(var linkProp in link.form){
				  jsonLink.form[linkProp] = link.form[linkProp];
			  }
			  for(var prop in link.cssStyle){
				  jsonLink.cssStyle[prop] = link.cssStyle[prop];
			  }
			  
			  //链接转折坐标
			  jsonLink.cssStyle.points = link.geometry.points;
			  jsonNode.linkArray.push(jsonLink);
		  }
	  }
    var jsResult = JSON.stringify(jsonTemplate).replace(/\&/g, "%26").replace(/\%/g, "%25").replace(/\+/g, "%2B");
	
    return jsResult;
}


// 选中某个单元
function selectCell() {

	if(!editStart){  //不是编辑状态
		return false;
	}
	
	// 处理前一个选中单元
	if(preSelectCell != null){
		
		if(preSelectCell.formName == "node"){
			// 清空节点变量表单
			clearVariable("nodeProp", preSelectCell);
		}else if(preSelectCell.formName == "link"){
		}else{
			clearVariable("templateProp", preSelectCell);
		}
	}

	var proDoc = null;
	if (typeof(graph.getSelectionCell()) == "object") { 
		
		window.bindCell = graph.getSelectionCell();  //绑定对象设置
		
		
		if(window.bindCell.vertex) // 如果是节点单元
		{
			var category = window.bindCell.form.category;
			if(category == "start" || category == "end"){  //开始和结束节点不显示
				
				document.all.nodePropertyWin.style.display = "none";
				document.all.linkPropertyWin.style.display = "none";
				document.all.templatePropertyWin.style.display = "none";
				return;
			}
			proDoc = document.getElementById("node");
			window.bindCell.formName = "node";

		}else{
			
			proDoc = document.getElementById("link");
			window.bindCell.formName = "link";
			
		}
	}else{// 如果选中模板

		window.bindCell = graph;   //绑定对象设置
		proDoc = document.getElementById("template");
		window.bindCell.formName = "template";
	}
	preSelectCell = window.bindCell;  //设置前一绑定对象
	
	// 重新显示表单
	proDoc.reset();   //清除表单
	
	document.all.nodePropertyWin.style.display = "none";
	document.all.linkPropertyWin.style.display = "none";
	document.all.templatePropertyWin.style.display = "none";
	if(typeof (graph.getSelectionCell()) == "object"){
		if(window.bindCell.vertex){ // 如果是节点单元
			document.all.nodePropertyWin.style.display = "";
			showVariable(nodeProp, window.bindCell);  // 展现节点变量表单
		}else{
			var cellStyle = graph.getCellStyle(window.bindCell);
			document.all.linkPropertyWin.style.display = "";
		}
	}else{
		document.all.templatePropertyWin.style.display = "";
		showVariable(templateProp, window.bindCell);  // 展现模板变量表单
	}
	

	//设置试图对象表单属性值	
	with (window.bindCell) {
		
		if(!window.bindCell.form){
			return;
		}
		window.bindCell.form.name = window.bindCell.value;

		//对图形单元的form对象属性循环
		for (var prop in window.bindCell.form) {

		if(typeof(proDoc[prop])=="object"){
			var fieldType = proDoc[prop].type;

			if(typeof(fieldType)=="undefined"){
			   fieldType = proDoc[prop][0].type;
			}

			if(fieldType=="text") // 如果是文本字段
			{
				$(proDoc[prop])[0].value = form[prop];
			}
			if(fieldType=="radio") // 如果是单选字段
			{
				$("input[@type=radio][@name="+prop+"][@value="+form[prop]+"]").attr("checked",true);
			}
			if(fieldType=="select-one") // 下拉框
			{
				$(proDoc[prop])[0].value = form[prop];
			}else{
				$(proDoc[prop])[0].value = form[prop];
			}
		}
		}
		proDoc.name.value = window.bindCell.value;
		if(formName=="node"){
		}
		if(formName=="link" && target && source){
			proDoc["inputNodeName"].value = window.bindCell.source.value;
			proDoc["outputNodeName"].value = window.bindCell.target.value;
		}

	}
}

/**
 * 显示源码
 * 
 * @param type
 * @return
 */
function showSource(type){
	
	var str = saveTemplate();;
	if(type == 'xml'){
		$.ajax({
			  type: "post",
			  url: initVar.basePath + startUrl + "jsonToXml.html",
			  data:{"act":"ajax","fileContent":str},
			  dataType: "json",
			  success: function(d){
				  alert(d.ajax_data);
			  }
		}); 
	}else{
		var win = window.open();
		win.document.write(str);
	}
}


// 流程数据效验
function validate(jsons){
	
	// 判断模板id是否为空
	if(jsons[0].form.templateId==""){
	alert("流程模板编号不能为空");return false;
	}
	if(jsons[0].form.aliases==""){
	alert("流程模板别名不能为空");return false;
	}
	if(jsons[0].form.name==""){
	alert("流程模板名不能为空");return false;
	}
	if(jsons[0].form.keywords==""){
	alert("流程模板关键字不能为空");return false;
	}
	if(jsons[0].form.endpoint==""){
	alert("流程模板回调服务的端地址不能为空");return false;
	}

	return true;
}

/**
 * 获得线条
 * @param lineStyle
 * @return
 */
function changeLine(lineStyle){

    graph.getModel().beginUpdate();
	var style = graph.getStylesheet().getDefaultEdgeStyle();
	style[mxConstants.STYLE_EDGE] = mxEdgeStyle[lineStyle];
	graph.getModel().endUpdate();
}

/**
 * 设置单元属性
 * @return
 */
function setCellProp(){
	
  try{
		if(!editStart){  //不是编辑状态
			return false;
		}
		
		if(typeof (graph.getSelectionCell()) != "object"){  //没有选中对象
			return false;
		}
		
		window.bindCell = graph.getSelectionCell();
		
		with(window.bindCell){
			
			if(vertex){ //如果是节点单元
				cssStyle.posLeft = geometry.x;
				cssStyle.posTop = geometry.y;
				cssStyle.posWidth = geometry.width;
				cssStyle.posHeight = geometry.height;
			}else{  // 连接
				
				if(typeof(form) == "undefined"){
					
					var id = getGenId();
					var jsonObj = {form:{"id":id,"name":""},cssStyle:{}};
					var link = new WorkFlowLink(jsonObj);
					link.draw(window.bindCell.source,null,window.bindCell);
				}
                if(!target || !source){  //没有目标(sourc 在选中的时候删除用到)
                	return false;
                }
				window.bindCell.cssStyle.fromX = source.cssStyle.posLeft;
				window.bindCell.cssStyle.fromY = source.cssStyle.posLeft;
				window.bindCell.cssStyle.toX = target.cssStyle.posTop;
				window.bindCell.cssStyle.toY = target.cssStyle.posTop;
				
				window.bindCell.form["inputNodeName"] = source.value;
				window.bindCell.form["outputNodeName"] = target.value;
				window.bindCell.form["inputNodeId"] = source.form.id;
				window.bindCell.form["outputNodeId"] = target.form.id;
				
				var linkName = window.bindCell.value;
				if(linkName == null || linkName == ""){
					linkName = "到" + target.value;
					window.bindCell.form.name = linkName;
					graph.cellLabelChanged(window.bindCell, linkName);
				}
			}
			//保存历史版本
			  //saveHistory();
		}
	   
	 }catch(e){
		 throw e;
	 }
}

//执行鼠标移动事件
function executeOnMouseMove(){

	setCellProp();  // 

}

//执行键盘按下事件
function executeKeyDown()
{
	if(event.ctrlKey && event.keyCode == 67){ // 复制
		copyNode();
	}
	if(event.ctrlKey && event.keyCode == 86){ // 粘贴
		pasteNode();
	}
	if(event.ctrlKey && event.keyCode == 90){ // 撤销
		undo();
	}
	if(event.ctrlKey && event.keyCode == 89){ // 重做
		redo();
	}
	if(event.keyCode == 46){ // 删除
		deleteSelectedCells();
	}
}

// 执行鼠标以上事件
function executeOnMouseOver(){
	
  //window.status = event.srcElement.outerHTML;
  
}

// 从属性窗口同步修改到某个单元
function synaCell(thisGet) {
	
    if(typeof(window.bindCell) == "undefined"){
    	return false;
    }
    var name = thisGet.name;
    var value = thisGet.value;
    var formName = window.bindCell.formName;
    	
    window.bindCell.form[thisGet.name] = thisGet.value;  // 同步
    
	if(formName=="node" || formName=="link"){
		graph.cellLabelChanged(window.bindCell,document.forms[formName].name.value);  // 修改cell
	}else if(formName=="template"){
		window.bindCell.value = document.forms["template"].name.value;
		document.all.tagTitles.children[0].innerText = document.forms["template"].name.value + "*";
	}
}

/**
 * 窗口属性即时保存功
 * @return
 */
function instantSave()
{
	$("input[@type=radio]").click(function(){synaCell(this);});
	
	$("textarea").change(function(){synaCell(this);});
	
	$("input[@type=checkbox]").click(function(){synaCell(this);});
	
	$("select").change(function(){synaCell(this);});
	
	$("input[@type=text]").keyup(function(){
		synaCell(this);
	});
	$("form[@name='staffSelect'] input[@type=text]").unbind("change");
	$("input[@type=radio]").each(function(){this.className = "radio";});
	$("input[@readonly]").each(function(){this.style.border=0;});
}

//执行鼠标释放调用方法
function exeMouseUp(){
	
	//setCellProp();
	saveHistory();
}

// 保存历史
function saveHistory(){

	//检测是否变化
	var nowJson = saveTemplate();
	if(graph.historyNum != 0){
		var hisJson = graph.historys[graph.historyNum];
		if(hisJson && nowJson == hisJson){
			return;
		}
	}
	graph.historys[graph.historyNum] = nowJson;
	graph.historyNum++;
	$("#show").html(graph.historyNum);
	//alert(graph.historyNum);
}



// 删除选中的单元
function deleteSelectedCells() {
	
	graph.getModel().beginUpdate();
	var cells = graph.getSelectionCells();
	var cellsDel = new Array();
	for(var i = 0; i< cells.length; i++){
		
		if(cells[i].form.category != "start" 
			&& cells[i].form.category != "end" ){ // 如果不是开始和结束节点
		}
		cellsDel.push(cells[i]);
	}
	
	
	graph.cellsRemoved(cellsDel);
	graph.getModel().endUpdate();
}


//删除所有的单元
function deleteAllCells(){
	
	graph.getModel().beginUpdate();
	var cells = graph.getChildVertices(graph.parent);
	graph.cellsRemoved(cells);
	graph.getModel().endUpdate();
}

// 复制节点
function copyNode(){
    
	var tempGraph = graph;
	graph.getModel().beginUpdate();
	window.newCells = new Array();
	var sourceCells = graph.getSelectionCells();
	for(var i = 0; i < sourceCells.length; i++){
		var cell = sourceCells[i];
		if(cell.form.category == "start" ||
				cell.form.category == "end"){
			alert("开始节点和结束节点不能复制");
			window.newCells = null;
			break;
		}
		window.newCells[i] = cell;
	}
	graph.getModel().endUpdate();
}

//粘贴节点
function pasteNode(){

	graph.getModel().beginUpdate();
	var copyCell;
	if(window.newCells == null || window.newCells.length == 0){
		return;
	}
	for(var i = 0;i < window.newCells.length;i++){
		copyCell = window.newCells[i].clone();
		copyCell.geometry.x = copyCell.geometry.x  +10;
		if(copyCell.vertex){
			copyCell.form.id = copyCell.form.id + "_1";
		}
		graph.addCell(copyCell,graph.parent,100,null,null);
		graph.selectCellForEvent(copyCell,null);
	}
	graph.getModel().endUpdate();
}


// 撤消(ctrl + z)
function undo(){
	
	if(graph.historyNum == 0){
		alert("不能撤销了，没有历史版本");
		return;
	}
	deleteAllCells();
	graph.historyNum--;
	var jsonStr = graph.historys[graph.historyNum];
	loadTemplate(jsonStr,true);
}



// 重做(ctrl + y)
function redo(){
	
	if(graph.historyNum == graph.historys.length){
		alert("不能再重做了，已还原到最新版本");
		return;
	}
	deleteAllCells();
	var jsonStr = graph.historys[graph.historyNum];
	graph.historyNum++;
	loadTemplate(jsonStr,true);
}


